package com.liuyi.netty.im.test.lychat.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.IdUtil;
import com.liuyi.netty.im.commons.codes.CodeConst;
import com.liuyi.netty.im.commons.codes.data.event.message.playload.Playload;
import com.liuyi.netty.im.server.util.ImHelp;
import com.liuyi.netty.im.server.util.ImUtil;
import com.liuyi.netty.im.test.lychat.LychatConst;
import com.liuyi.rapid.develop.tool.resp.Response;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

import static com.liuyi.rapid.develop.tool.resp.ResponseCall.success;
import static com.liuyi.rapid.develop.tool.resp.ResponseCall.successMsg;
import static org.springframework.http.ResponseEntity.ok;

/**
 * @author Mr.Fmy
 * @since 2022/1/20
 */
@RestController
@RequestMapping
@Validated
public class ChatController {

    /**
     * 登录
     *
     * @param userId 用户id
     */
    @PostMapping("/login/{userId}")
    public ResponseEntity<Response<String>> login(@PathVariable String userId) {
        StpUtil.login(userId);
        StpUtil.getSession().set("nick", userId).set("head", LychatConst.DEFAULT_USER_HEAD);
        return ok(success(StpUtil.getTokenValue()));
    }


    /**
     * 发送消息
     */
    @PostMapping("/sendMessage")
    public ResponseEntity<Response<Void>> createMessage(@Valid @RequestBody CahtModel.SendMessage p) {
        Playload playload = ImUtil.decodePlayload(p.getContent(), p.getMsgType().getTClass());
        CodeConst.SessionType sessionType = ImHelp.sessionIdToType(p.getSessionId());
        String toId = ImHelp.sessionIdToId(p.getSessionId());
        for (int i = 0; i < p.getQps(); i++) {
            switch (sessionType) {
                case C2C:
                    ImUtil.c2cMessage(IdUtil.fastSimpleUUID(), System.currentTimeMillis(), p.getFromId(), toId, p.getMsgType(), playload);
                    break;
                case GROUP:
                    ImUtil.groupMessage(IdUtil.fastSimpleUUID(), System.currentTimeMillis(), p.getFromId(), toId, p.getMsgType(), playload);
                    break;
            }
        }
        return ok(successMsg("OK"));
    }
}
